package com.jf3q.sup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf3q.sup.domain.*;
import com.jf3q.sup.dto.SalesOrderDetailsDto;
import com.jf3q.sup.dto.SalesOrdersDto;
import com.jf3q.sup.mapper.*;
import com.jf3q.sup.service.OutboundShipmentsService;
import com.jf3q.sup.service.SalesOrdersService;
import com.jf3q.sup.utils.Constant;
import com.jf3q.sup.vo.SaleShowIndexVo;
import com.jf3q.sup.vo.SalesOrderDetailsVo;
import com.jf3q.sup.vo.SalesOrdersVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class SalesOrdersServiceImpl extends ServiceImpl<SalesOrdersMapper, SalesOrders>
        implements SalesOrdersService {
    @Autowired
    private OutboundShipmentsMapper outboundShipmentsMapper;
    @Autowired
    private OutboundShipmentDetailsMapper outboundShipmentDetailsMapper;
    @Autowired
    private ProductsMapper productsMapper;

    @Autowired
    private SalesOrderDetailsMapper salesOrderDetailsMapper;

    @Override
    public IPage<SalesOrdersVo> pages(SalesOrdersDto salesOrdersDto, Integer pageNum) {
        IPage<SalesOrdersVo> page = Page.of(pageNum, Constant.PAGE_SIZE);
        page = baseMapper.selectPages(new Page<>(page.getCurrent(), page.getSize()), salesOrdersDto);
        return page;
    }

    @Override
    public void addOrUpdate(SalesOrdersDto salesOrdersDto) {
        boolean flag = salesOrdersDto.getId() == null || salesOrdersDto.getId() == 0 ? true : false;
        try {
            //销售订单类
            SalesOrders salesOrders = new SalesOrders();

            BeanUtils.copyProperties(salesOrdersDto, salesOrders);

            //计算商品的价格
            BigDecimal sum = BigDecimal.valueOf(0.00);
            for (SalesOrderDetailsDto salesOrderDetailsDto : salesOrdersDto.getSalesOrderDetailsDto()) {
                //查询商品信息
                Products products = productsMapper.selectById(salesOrderDetailsDto.getProductId());
                //判断商品库存是否足够
                if (!isStockQuantity(products,salesOrders.getId(),salesOrderDetailsDto.getQuantity())){
                    throw new RuntimeException(products.getName()+"的库存不足");
                }else {
                    //扣减库存
                    products.setStockQuantity(products.getStockQuantity()-salesOrderDetailsDto.getQuantity());
                    productsMapper.updateById(products);
                }
                //当前商品的总价
                BigDecimal sumPrice = products.getPrice().multiply(BigDecimal.valueOf(salesOrderDetailsDto.getQuantity()));
                //累加所有商品的价格
                sum = sum.add(sumPrice);
            }

            //计算总金额
            salesOrders.setTotalAmount(sum);

            //出库表类
            OutboundShipments shipments=new OutboundShipments()
                    .setCarrierId(salesOrdersDto.getCarrierId())
                    .setStatus(1)
                    .setShipmentDate(new Date());
            if (flag) {
////                新增销售订单
//                salesOrders.setState(1);
                baseMapper.insert(salesOrders);
//                新增出库信息
                outboundShipmentsMapper.insert(shipments);
            } else {
                //修改销售订单
                baseMapper.updateById(salesOrders);

            }

            if (!flag){
                //根据销售订单id删除销售订单明细
                salesOrderDetailsMapper.delete(
                        new LambdaQueryWrapper<SalesOrderDetails>()
                                .eq(SalesOrderDetails::getOrderId,salesOrders.getId()));
            }

            for (SalesOrderDetailsDto salesOrderDetailsDto : salesOrdersDto.getSalesOrderDetailsDto()) {
                //查询商品信息
                Products products = productsMapper.selectById(salesOrderDetailsDto.getProductId());
                //订单详情类
                SalesOrderDetails salesOrderDetails = new SalesOrderDetails()
                        .setOrderId(salesOrders.getId())
                        .setProductId(salesOrderDetailsDto.getProductId())
                        .setQuantity(salesOrderDetailsDto.getQuantity())
                        .setPrice(products.getPrice());

//                出库类
                OutboundShipmentDetails shipmentDetails=new OutboundShipmentDetails()
                        .setOutboundShipmentId(shipments.getId())
                        .setProductId(products.getId())
                        .setQuantity(salesOrderDetailsDto.getQuantity());
                if (flag) {
                    //新增销售订单明细
                    salesOrderDetailsMapper.insert(salesOrderDetails);

                    //新增出库详情订单
                    outboundShipmentDetailsMapper.insert(shipmentDetails);
                } else {
                    //修改销售订单明细
                    salesOrderDetailsMapper.insert(salesOrderDetails);
                }
            }
        } catch (BeansException e) {
            System.out.println(e);
            throw new RuntimeException("添加失败！");
        }
    }

    @Override
    public void del(Integer[] ids) {

        for (int i = 0; i < ids.length; i++) {
            //删除销售订单明细
            salesOrderDetailsMapper.delete(
                    new LambdaQueryWrapper<SalesOrderDetails>().eq(SalesOrderDetails::getOrderId, ids[i])
            );
            //删除销售订单
            baseMapper.deleteById(ids[i]);
        }

    }



    @Override
    public SalesOrdersVo getOrders(Integer id) {
        return baseMapper.selectOrders(id);
    }

    @Override
    public List<SaleShowIndexVo> getSaleShow(String time) {
        return salesOrderDetailsMapper.getSaleShowList(time);
    }

    //判断库存
    public boolean isStockQuantity(Products products,Integer ordersId,Integer quantity){
        if (ordersId!=null){
            //通过,ordersId获取销售订单详情
            List<SalesOrderDetails> salesOrderDetails = salesOrderDetailsMapper.selectList(
                    new LambdaQueryWrapper<SalesOrderDetails>()
                            .eq(SalesOrderDetails::getOrderId, ordersId));

            if (salesOrderDetails!=null){
                for (SalesOrderDetails salesOrderDetail : salesOrderDetails) {
                    if (products.getId()!=salesOrderDetail.getProductId()){
                        continue;
                    }
                    //库存不足
                    if ((products.getStockQuantity()+salesOrderDetail.getQuantity())<quantity){
                        return false;
                    }
                    //库存充足归还数量重新扣减库存
                    products.setStockQuantity(products.getStockQuantity()+salesOrderDetail.getQuantity());
                    productsMapper.updateById(products);
                    return true;
                }
            }
        }

        //库存不足
        if (products.getStockQuantity()<quantity){
            return false;
        }

        return true;
    }

}




